package com.hirsi.module.file.service;

import com.hirsi.core.vo.param.PageParam;
import com.hirsi.core.vo.result.PageResult;
import com.hirsi.module.file.vo.param.QueryFileParam;
import com.hirsi.module.file.vo.result.FileResult;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileService {

    public static PageResult<FileResult> query(PageParam page, QueryFileParam param) {
        List<FileResult> results = new ArrayList<>();
        int startIndex = (page.getCurrent() - 1) * page.getSize();
        int total = 0;
        if (param.getPath() == null || param.getPath().isEmpty()) {
            File[] files = File.listRoots();
            if (files != null && files.length > 0) {
                total = files.length;
                int endIndex = Math.min(startIndex + page.getSize(), files.length);
                FileSystemView fsv = FileSystemView.getFileSystemView();
                for (int i = startIndex; i < endIndex; i++) {
                    results.add(new FileResult(fsv.getSystemDisplayName(files[i]), files[i].getPath()));
                }
            }
        } else {
            File file = new File(param.getPath());
            if (file.exists()) {
                File[] files = file.listFiles();
                if (files != null && files.length > 0) {
                    total = files.length;
                    int endIndex = Math.min(startIndex + page.getSize(), files.length);
                    for (int i = startIndex; i < endIndex; i++) {
                        results.add(new FileResult(files[i].getName(), files[i].getPath()));
                    }
                }
            }
        }
        return new PageResult<>(page.getCurrent(), page.getSize(), (int) Math.ceil(total / page.getSize().doubleValue()), total, results);
    }
}
